package com.example.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http // 关闭csrf防护
            .csrf().disable()
            .headers().frameOptions().disable()
            .and();
        http //登录处理
            .formLogin() //表单方式，或httpBasic
            .loginPage("/signin")
            .loginProcessingUrl("/loginForm")
            .defaultSuccessUrl("/index") //成功登陆后跳转页面
            .failureUrl("/signin?error")
            .permitAll()
            .and();
        http //授权配置
            .authorizeRequests()
            //无需权限访问
            .antMatchers("/css/**", "/js/**", "/img/**", "/*.*", "/error404").permitAll()
            //登录并且有相应角色才可访问
            .antMatchers("/admin/**", "/admin").hasRole("ADMIN")
            .antMatchers("/user/**", "/user").hasRole("USER")
            //其他接口需要登录后才能访问
            .anyRequest().authenticated()
            .and();
    }
}

